package cn.study.luckyapp.activity.command;

import cm.study.config.util.FileLoad;
import cn.study.luckyapp.listener.AwardInventoryToRedisApplicationListener;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.List;


@Slf4j
@Component
@AllArgsConstructor
public class RedisDeductionNumberExe {
    private RedisTemplate<String,Object> redisTemplate;

    public Integer execute(Long activityId,Long awardId){
       Integer result=InvokeDeductionInventory(AwardInventoryToRedisApplicationListener.getKey(awardId,activityId));
        return result;
    }
    public Integer InvokeDeductionInventory(String key){
        DefaultRedisScript defaultRedisScript=new DefaultRedisScript();
        defaultRedisScript.setScriptText("local key = KEYS[1]\n" +
                "local usedstore = tonumber(redis.call('get', key))\n" +
                "if usedstore ~= nil and usedstore > 0 then\n" +
                "    local current = tonumber(redis.call('decr', key))\n" +
                "    return current\n" +
                "end\n" +
                "--若此时库存为0,则直接返回-1,不写redis;在库存不足时减小写压力(1次扣减 + 1次回滚)\n" +
                "if usedstore ~= nil and usedstore == 0 then\n" +
                "    return -1\n" +
                "end\n" +
                "return usedstore\n");
        defaultRedisScript.setResultType(Long.class);
        Long result= (Long) redisTemplate.opsForValue().getOperations().execute(defaultRedisScript,List.of(key));
        if(result==-1){
            return 0;
        }
        return 1;
    }
}
